import {
	Card,
	Empty,
	Input,
	Space,
	message,
	Row,
	Col,
	List,
	Drawer,
} from "antd";
import {
	SearchOutlined,
	FolderOutlined,
	RightOutlined,
	MenuOutlined,
	MenuFoldOutlined,
	MenuUnfoldOutlined,
} from "@ant-design/icons";
import { useState, useEffect } from "react";
import { Form } from "antd";
import type { TaskItem, CategoryItem } from "@/api/services/taskService";
import taskService from "@/api/services/taskService";
import { convertFormDataToSubmit } from "./utils/taskUtils";
import TaskTable from "./components/TaskTable";
import TaskDetailModal from "./components/TaskDetailModal";
import { useMediaQuery } from "@/hooks/useMediaQuery";
import "./index.less";

const TaskPage = () => {
	const [loading, setLoading] = useState(false);
	const [taskList, setTaskList] = useState<TaskItem[]>([]);
	const [total, setTotal] = useState(0);
	const [currentPage, setCurrentPage] = useState(1);
	const [pageSize, setPageSize] = useState(10);
	const [keyword, setKeyword] = useState("");
	const [detailVisible, setDetailVisible] = useState(false);
	const [currentTask, setCurrentTask] = useState<TaskItem>();
	const [categories, setCategories] = useState<CategoryItem[]>([]);
	const [selectedCategory, setSelectedCategory] = useState<number | null>(null);
	const [drawerVisible, setDrawerVisible] = useState(false);
	const [categoryCollapsed, setCategoryCollapsed] = useState(false);
	const [form] = Form.useForm();

	const isMobile = useMediaQuery("(max-width: 768px)");

	// 获取任务列表
	const fetchTaskList = async (params: {
		page: number;
		keyword?: string;
		category_id?: number;
	}) => {
		try {
			setLoading(true);
			const res = await taskService.taskList({
				page: params.page,
				limit: pageSize,
				keyword: params.keyword || "",
				category_id: params.category_id || undefined,
			});
			setTaskList(res.items);
			setTotal(res.total);
		} catch (error) {
			message.error("获取任务列表失败");
		} finally {
			setLoading(false);
		}
	};

	// 获取分类列表
	const fetchCategories = async () => {
		try {
			const res = await taskService.categoryList({
				page: 1,
				limit: 100,
			});
			setCategories(res.items);
		} catch (error) {
			message.error("获取分类列表失败");
		}
	};

	useEffect(() => {
		fetchCategories();
		fetchTaskList({ page: 1 });
	}, []);

	const handleSubmit = async () => {
		if (!currentTask) return;

		try {
			const values = await form.validateFields();
			const submitData = convertFormDataToSubmit(
				values.formList,
				currentTask.id,
			);
			await Promise.all(submitData.map((data) => taskService.taskSubmit(data)));
			message.success("任务提交成功");
			setDetailVisible(false);
			form.resetFields();
			fetchTaskList({
				page: currentPage,
				keyword,
				category_id: selectedCategory,
			});
		} catch (error) {
			if (error.errorFields) {
				message.error("请填写必填项");
			} else {
				message.error("任务提交失败");
			}
		}
	};

	const handleViewDetail = async (task: TaskItem) => {
		try {
			const detail = await taskService.taskInfo(task.id);
			setCurrentTask(detail);
			setDetailVisible(true);
			form.resetFields();
		} catch (error) {
			message.error("获取任务详情失败");
		}
	};

	const handleSearch = (value: string) => {
		setKeyword(value.trim());
		setCurrentPage(1);
		fetchTaskList({
			page: 1,
			keyword: value.trim(),
			category_id: selectedCategory,
		});
	};

	const handlePageChange = (page: number, size: number) => {
		setCurrentPage(page);
		setPageSize(size);
		fetchTaskList({ page, keyword, category_id: selectedCategory });
	};

	const handleModalCancel = () => {
		setDetailVisible(false);
		form.resetFields();
	};

	const handleCategorySelect = (categoryId: number | null) => {
		setSelectedCategory(categoryId);
		setCurrentPage(1);
		fetchTaskList({ page: 1, keyword, category_id: categoryId });
		if (isMobile) {
			setDrawerVisible(false);
		}
	};

	const CategoryList = () => (
		<div className="p-4">
			<List
				dataSource={[{ id: null, name: "全部任务" }, ...categories]}
				renderItem={(category) => (
					<List.Item
						className={`px-4 py-3 rounded cursor-pointer hover:bg-gray-50 ${
							selectedCategory === category.id ? "bg-gray-50" : ""
						}`}
						onClick={() => handleCategorySelect(category.id)}
					>
						<Space size="middle">
							<FolderOutlined
								className={
									selectedCategory === category.id
										? "text-blue-500"
										: "text-gray-400"
								}
							/>
							<span
								className={
									selectedCategory === category.id
										? "text-blue-500 font-medium"
										: "text-gray-600"
								}
							>
								{category.name}
							</span>
						</Space>
						{selectedCategory === category.id && (
							<RightOutlined className="text-blue-500" />
						)}
					</List.Item>
				)}
			/>
		</div>
	);

	return (
		<div className="task-page">
			<Row gutter={[24, 24]}>
				{!isMobile && !categoryCollapsed && (
					<Col md={6}>
						<Card bordered={false} style={{ padding: 0 }}>
							<div className="py-4 px-6 border-b border-gray-200 flex justify-between items-center">
								<div className="text-lg font-medium">任务分类</div>
								<div
									className="p-1 rounded hover:bg-gray-100 cursor-pointer"
									onClick={() => setCategoryCollapsed(true)}
								>
									<MenuFoldOutlined className="text-lg text-gray-400" />
								</div>
							</div>
							<CategoryList />
						</Card>
					</Col>
				)}
				<Col xs={24} md={categoryCollapsed ? 24 : 18}>
					<Card className="search-card">
						<div className="flex items-center gap-4">
							{(isMobile || categoryCollapsed) && (
								<div
									className="p-2 rounded hover:bg-gray-100 cursor-pointer"
									onClick={() =>
										isMobile
											? setDrawerVisible(true)
											: setCategoryCollapsed(false)
									}
								>
									{categoryCollapsed ? (
										<MenuUnfoldOutlined className="text-lg" />
									) : (
										<MenuOutlined className="text-lg" />
									)}
								</div>
							)}
							<Input.Search
								placeholder="搜索任务..."
								allowClear
								enterButton={
									<>
										<SearchOutlined /> 搜索
									</>
								}
								size="large"
								onSearch={handleSearch}
								className="flex-1"
							/>
						</div>
					</Card>

					<div className="content-container mt-6">
						<TaskTable
							loading={loading}
							taskList={taskList}
							currentPage={currentPage}
							pageSize={pageSize}
							total={total}
							onPageChange={handlePageChange}
							onViewDetail={handleViewDetail}
						/>

						<TaskDetailModal
							visible={detailVisible}
							currentTask={currentTask}
							form={form}
							onCancel={handleModalCancel}
							onSubmit={handleSubmit}
						/>
					</div>
				</Col>
			</Row>

			{isMobile && (
				<Drawer
					title="任务分类"
					placement="left"
					onClose={() => setDrawerVisible(false)}
					open={drawerVisible}
					width="80%"
					bodyStyle={{ padding: 0 }}
				>
					<CategoryList />
				</Drawer>
			)}
		</div>
	);
};

export default TaskPage;
